package palindrome;

import java.util.ArrayList;
import java.util.List;

public class PalPartition {

	public static void main(String[] args) {
		PalPartition palPartition = new PalPartition();
		ArrayList<ArrayList<String>> list = palPartition.partition("google");
		for (ArrayList<String> arrayList : list) {
			System.out.println(arrayList);
		}
	}
	public ArrayList<ArrayList<String>> partition(String s) {
		ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
		helper(ret, new ArrayList<String>(), s, 0);
		return ret;
	}

	private void helper(List<ArrayList<String>> ret, List<String> list, String s, int pos) {
		if (pos == s.length()) {
			ret.add(new ArrayList<String>(list));
			return;
		}
		for (int i = pos; i < s.length(); i++) {
			//只在从position 到 i 是回文串的时候进入循环
			if (isPal(s, pos, i)) {
				list.add(s.substring(pos, i + 1));
				System.out.println(" list " + list);
				helper(ret, list, s, i + 1);
				//在pos == s.length的时候已经将List加入到了set中，故要将其中的子串删除，寻找下一个
				list.remove(list.size() - 1);
				System.out.println("after remove  list " + list);
			}
		}
	}

	//判断s是否是回文串
	private boolean isPal(String s, int i, int j) {
		char[] string = s.toCharArray();
		while (i <= j) {
			if (string[i++] != string[j--])
				return false;
		}
		return true;
	}
}
